/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xui_lib.component.picker.widget;


import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.TouchEvent;

import com.xuexiang.xui_lib.ResourceTable;
import com.xuexiang.xui_lib.component.picker.widget.configure.PickerOptions;


/**
 * 精仿iOSPickerViewController控件
 *
 * @author xuexiang
 * @since 2019/1/1 下午6:58
 */
public class BasePickerView {

    private Context context;
    protected StackLayout contentContainer;
    private ComponentContainer dialogView;//附加Dialog 的 根View

    protected PickerOptions mPickerOptions;

    protected PopupDialog mDialog;
    protected CommonDialog mCommonDialog;
    protected Component clickView;//是通过哪个View弹出的
    private AnimatorProperty popIntproperty;
    private AnimatorProperty popOutproperty;
    private AnimatorProperty comIntproperty;
    private AnimatorProperty comOutproperty;
    private StackLayout.LayoutConfig params;

    public BasePickerView(Context context) {
        this.context = context;
    }

    protected void initViews() {
        if (isDialog()) {
            params = new StackLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT, LayoutAlignment.BOTTOM);
            params.setMarginLeft(10);
            params.setMarginRight(10);
        } else {
            params = new StackLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT, LayoutAlignment.CENTER);
            params.setMarginLeft(100);
            params.setMarginRight(100);
        }
        LayoutScatter layoutScatter = LayoutScatter.getInstance(context);
        dialogView = (ComponentContainer) layoutScatter.parse(ResourceTable.Layout_xui_layout_picker_view_base, null, false);
        //设置界面的背景为透明
        ShapeElement backgroundElement = new ShapeElement();
        backgroundElement.setRgbColor(new RgbColor(Color.TRANSPARENT.getValue()));
        dialogView.setBackground(backgroundElement);
        //这个是真正要加载选择器的父布局
        contentContainer = (StackLayout) dialogView.findComponentById(ResourceTable.Id_content_container);
        //设置对话框 默认左右间距屏幕30
        contentContainer.setLayoutConfig(params);
        if (isDialog()) {
            createDialog();
            //给背景设置点击事件,这样当点击内容以外的地方会关闭界面
        } else {
            createComDialog();
        }
        setKeyBackCancelable(true);
    }

    /**
     * show方法
     *
     * @param v (是通过哪个View弹出的)
     * @param isAnim 是否显示动画效果
     */
    public void show(Component v, boolean isAnim) {
        this.clickView = v;
        show();
    }

    /**
     * 添加View到根视图
     */
    public void show() {
        if (isDialog()) {
            showDialog();
        } else {
            showComDialog();
        }
    }


    public void dismiss() {
        if (isDialog()) {
            dismissDialog();
        } else {
            dismissComDialog();
        }
    }


    public void setKeyBackCancelable(boolean isCancelable) {
        dialogView.setKeyEventListener(onKeyBackListener);
    }

    private ComponentContainer.KeyEventListener onKeyBackListener = new ComponentContainer.KeyEventListener() {
        @Override
        public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.KEY_BACK && keyEvent.getKeyDownDuration() == KeyEvent.KEY_PAGE_DOWN) {
                dismiss();
                return true;
            }
            return false;
        }
    };

    protected BasePickerView setOutSideCancelable(boolean isCancelable) {
        return this;
    }

    /**
     * 设置对话框模式是否可以点击外部取消
     */
    public void setDialogOutSideCancelable() {
        if (mDialog != null) {
            mDialog.setAutoClosable(mPickerOptions.cancelable);
        }
    }

    public void setComDialogOutSideCancelable() {
        if (mCommonDialog != null) {
            mCommonDialog.setAutoClosable(mPickerOptions.cancelable);
        }
    }


    /**
     * Called when the user touch on black overlay, in order to dismiss the dialog.
     */
    private final ComponentContainer.TouchEventListener onCancelableTouchListener = new ComponentContainer.TouchEventListener() {
        @Override
        public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
            if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
                dismiss();
            }
            return false;
        }

    };


    public Component findViewById(int id) {
        return contentContainer.findComponentById(id);
    }


    private void createDialog() {
        if (dialogView != null) {
            mDialog = new PopupDialog(context, null);
            popIntproperty = createAnimInPop();
            popOutproperty = createAnimOutPop();
            mDialog.setSize(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
            mDialog.setAutoClosable(mPickerOptions.cancelable);//不能点外面取消,也不能点back取消
            mDialog.setCustomComponent(dialogView);

            //开始 动画
            popIntproperty.setTarget(dialogView);
            //关闭 动画
            popOutproperty.setTarget(dialogView);

            mDialog.setTransparent(true);
            mDialog.setAlignment(LayoutAlignment.BOTTOM);
            mDialog.setDialogListener(new BaseDialog.DialogListener() {
                @Override
                public boolean isTouchOutside() {
                    System.out.println("==========isTouchOutside===========");
                    dismissDialog();
                    return false;
                }
            });
        }
    }

    private void createComDialog() {
        if (dialogView != null) {
            mCommonDialog = new CommonDialog(context);
            comIntproperty = createAnimIntCom();
            comOutproperty = createAnimOutCom();
            mCommonDialog.setSize(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
            mCommonDialog.setAutoClosable(mPickerOptions.cancelable);//不能点外面取消,也不能点back取消
            mCommonDialog.setContentCustomComponent(dialogView);
            comIntproperty.setTarget(dialogView);
            comOutproperty.setTarget(dialogView);
            mCommonDialog.setTransparent(true);
            mCommonDialog.setAlignment(LayoutAlignment.CENTER);
            mCommonDialog.setDialogListener(new BaseDialog.DialogListener() {
                @Override
                public boolean isTouchOutside() {
                    dismissComDialog();
                    return false;
                }
            });
        }
    }

    private void showDialog() {
        if (mDialog != null) {
            mDialog.show();
            popIntproperty.start();
        }
    }

    private void showComDialog() {
        if (mCommonDialog != null) {
            mCommonDialog.show();
            comIntproperty.start();
        }
    }


    private void dismissDialog() {
        popOutproperty.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {

            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                if (mDialog != null) {
                    if (mPickerOptions.onDismissListener != null) {
                        mPickerOptions.onDismissListener.onDismiss(BasePickerView.this);
                    }
                    mDialog.destroy();
                }
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        }).start();
    }

    private void dismissComDialog() {
        comOutproperty.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {

            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                if (mCommonDialog != null) {
                    if (mPickerOptions.onDismissListener != null) {
                        mPickerOptions.onDismissListener.onDismiss(BasePickerView.this);
                    }
                    mCommonDialog.destroy();
                }
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        }).start();

    }

    public ComponentContainer getDialogContainerLayout() {
        return contentContainer;
    }

    public PopupDialog getDialog() {
        return mDialog;
    }

    public CommonDialog getComDialog() {
        return mCommonDialog;
    }

    public boolean isDialog() {
        return true;
    }

    private AnimatorProperty createAnimInPop() {
        AnimatorProperty animator = new AnimatorProperty();
        animator.moveFromY(200).moveToY(0).alphaFrom(0).alpha(1).setDuration(200);
        return animator;
    }

    private AnimatorProperty createAnimOutPop() {
        AnimatorProperty animator = new AnimatorProperty();
        animator.moveFromY(0).moveToY(200).alphaFrom(1).alpha(0).setDuration(200);
        return animator;
    }

    private AnimatorProperty createAnimIntCom() {
        AnimatorProperty animator = new AnimatorProperty();
        animator.scaleXFrom(0.5f).scaleX(1f).scaleYFrom(0.5f).scaleY(1f).alphaFrom(0).alpha(1).setDuration(200);
        return animator;
    }

    private AnimatorProperty createAnimOutCom() {
        AnimatorProperty animator = new AnimatorProperty();
        animator.scaleXFrom(1f).scaleX(0.5f).scaleYFrom(1f).scaleY(0.5f).alphaFrom(1).alpha(0).setDuration(200);
        return animator;
    }


}
